package fr.afcepf.projet.hebergeur.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import fr.afcepf.projet.hebergeur.dao.interfaces.IClientDao;
import fr.afcepf.projet.hebergeur.data.Abonnement;
import fr.afcepf.projet.hebergeur.data.Client;
import fr.afcepf.projet.hebergeur.dto.ClientDto;
import fr.afcepf.projet.hebergeur.exception.ServiceException;
import fr.afcepf.projet.hebergeur.service.interfaces.IServiceClients;

@Service("serviceClient")
@Transactional
public class ServiceClientsImpl implements IServiceClients{
	//@Inject
	@Resource
	IClientDao dao;
	

	public IClientDao getDao() {
		return dao;
	}

	public void setDao(IClientDao dao) {
		this.dao = dao;
	}
	
	private ClientDto convertToDto(Client  c){
		ClientDto cDto = new ClientDto();
		BeanUtils.copyProperties(c, cDto);
		cDto.setNumero(c.getNumClient());
		return cDto;
	}
	
	private Client convertToEntity(ClientDto dto) {
		Client entity = new Client();
		BeanUtils.copyProperties(dto, entity);
		entity.setNumClient(dto.getNumero());
		return entity;
	}

	@Override
	public ClientDto createClient() {
		Client c = dao.persistNewEntity(new Client());
		dao.updateEntity(c);
		ClientDto cdto = convertToDto(c); 
		return cdto;
	}	

	@Override
	public void modifierClient(ClientDto clientDto) {
		Client client = this.convertToEntity(clientDto);
		this.dao.updateEntity(client);
	}

	@Override
	public void removeClient(ClientDto clientDto) {
		this.dao.deleteEntity(Client.class, clientDto.getNumero());
	}

	@Override
	public ClientDto getClientSelonNumero(Long numero) throws ServiceException {
		Client c = dao.getEntityByPrimaryKey(Client.class, numero);
		return c == null ? null : convertToDto(c);
	}

	@Override
	public Collection<ClientDto> getTousLesClients() throws ServiceException {
		Collection<Client> listeClients = dao.getAllClients();
		Collection<ClientDto> listeCliDto = new  ArrayList<ClientDto>();
		for(Client c: listeClients)
			listeCliDto.add((ClientDto) convertToDto(c));
		return listeCliDto;
	}

	@Override
	public Double getTotalPrixAboOfClient(Long numcli) throws ServiceException{
		Double total = 0.0;
		Client c = dao.getEntityByPrimaryKey(Client.class, numcli);
		Collection<Abonnement> abos = c.getAbonnements();
		for (Abonnement abonnement : abos) {
			total += abonnement.getPrix() == null ? 0 : abonnement.getPrix();
		}
		return total;
	}

}
